package com.example.smartgreenhouse.interceptor;

import com.example.smartgreenhouse.annotation.JwtToken;
import com.example.smartgreenhouse.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class JwtInterceptor implements HandlerInterceptor {

	@Autowired
	private JwtUtil jwtUtil;
    /*
    preHandle方法在请求处理之前被调用。
	可以用于进行JWT的验证。
	*/
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		//从请求头里面取出需要验证的JwtToken
		String token = request.getHeader("token");

		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		// 检查方法是否有 JwtToken 注解
		if (method.isAnnotationPresent(JwtToken.class)) {
			JwtToken jwtToken = method.getAnnotation(JwtToken.class);

			// 检查注解的 required 属性，默认是 true
			if (jwtToken.required()) {
				if ("".equals(token)||token==null) {
					response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
					response.setContentType("application/json");
					String timestamp = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME);
					// 设置状态码
					int status = HttpServletResponse.SC_UNAUTHORIZED;
					String error = "Unauthorized";
					String message = "Token is missing, please log in.";
					// 构建 JSON 响应
					String jsonResponse = String.format("{\"timestamp\": \"%s\", \"status\": %d, \"error\": \"%s\", \"message\": \"%s\", \"path\": \"%s\"}",
							timestamp, status, error, message,request.getRequestURI());
					response.getWriter().write(jsonResponse);
					return false; // 返回 false 表示拦截请求
				}
				if (jwtUtil.checkSign(token) == null) {
					response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
					response.setContentType("application/json");
					String timestamp = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME);
					int status = HttpServletResponse.SC_UNAUTHORIZED;
					String error = "Unauthorized";
					String message = "Token is invalid!";
					// 构建 JSON 响应
					String jsonResponse = String.format("{\"timestamp\": \"%s\", \"status\": %d, \"error\": \"%s\", \"message\": \"%s\", \"path\": \"%s\"}",
							timestamp, status, error, message,request.getRequestURI());
					response.getWriter().write(jsonResponse);
					return false; // 返回 false 表示拦截请求
				}
			}
		}
	return true; // 继续处理请求
	}
}
